package com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.api;

import cn.hutool.json.JSONUtil;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.dto.PPTCreateResponse;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.dto.PPTDirectCreateRequest;
import com.eduagent.xwqeduagent.api.IntelligentPPTGeneration.util.ApiAuthAlgorithm;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;

/**
 * 直接生成PPT的API
 * 调用讯飞开放平台直接生成PPT
 */
@Slf4j
@Component
public class PPTDirectCreator {

    @Value("${xunfei.api.ppt.direct-create-url:https://zwapi.xfyun.cn/api/ppt/v2/create}")
    private String directCreateUrl;

    @Value("${xunfei.api.ppt.app-id}")
    private String appId;

    @Value("${xunfei.api.ppt.api-key}")
    private String apiKey;

    private final static OkHttpClient client = new OkHttpClient().newBuilder()
            .connectionPool(new ConnectionPool(100, 5, TimeUnit.MINUTES))
            .readTimeout(120, TimeUnit.SECONDS) // 增加超时时间，因为PPT生成可能需要更长时间
            .build();

    /**
     * 直接生成PPT
     *
     * @param request 请求参数
     * @param file    上传的文件（可为null，如果使用query或fileUrl）
     * @return PPT生成响应
     */
    public PPTCreateResponse createPPTDirect(PPTDirectCreateRequest request, MultipartFile file) {
        try {
            log.info("开始直接生成PPT，参数: {}", JSONUtil.toJsonStr(request));
            
            // 获取时间戳和签名
            long timestamp = System.currentTimeMillis()/1000;
            String ts = String.valueOf(timestamp);

            ApiAuthAlgorithm auth = new ApiAuthAlgorithm();
            String signature = auth.getSignature(appId, apiKey, timestamp);
            
            // 构建multipart请求
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
            
            // 添加请求参数
            if (request.getQuery() != null && !request.getQuery().trim().isEmpty()) {
                builder.addFormDataPart("query", request.getQuery());
            }
            
            if (request.getBusinessId() != null) {
                builder.addFormDataPart("businessId", request.getBusinessId());
            }
            
            if (request.getTemplateId() != null) {
                builder.addFormDataPart("templateId", request.getTemplateId());
            }
            
            if (request.getAuthor() != null) {
                builder.addFormDataPart("author", request.getAuthor());
            }
            
            if (request.getIsCardNote() != null) {
                builder.addFormDataPart("isCardNote", request.getIsCardNote().toString());
            }
            
            if (request.getSearch() != null) {
                builder.addFormDataPart("search", request.getSearch().toString());
            }
            
            if (request.getLanguage() != null) {
                builder.addFormDataPart("language", request.getLanguage());
            }
            
            if (request.getIsFigure() != null) {
                builder.addFormDataPart("isFigure", request.getIsFigure().toString());
            }
            
            if (request.getAiImage() != null) {
                builder.addFormDataPart("aiImage", request.getAiImage());
            }
            
            // 处理输入内容
            boolean hasInputContent = false;
            
            // 检查是否有文本查询
            if (request.getQuery() != null && !request.getQuery().trim().isEmpty()) {
                hasInputContent = true;
            }
            
            // 处理文件
            if (file != null && !file.isEmpty()) {
                // 使用上传的文件
                builder.addFormDataPart("file", request.getFileName(),
                        RequestBody.create(file.getBytes(), MediaType.parse("application/octet-stream")));
                hasInputContent = true;
            } else if (request.getFileUrl() != null && !request.getFileUrl().trim().isEmpty()) {
                // 使用文件URL
                builder.addFormDataPart("fileUrl", request.getFileUrl());
                hasInputContent = true;
            }
            
            // 如果使用文件，添加文件名
            if ((file != null || request.getFileUrl() != null) && request.getFileName() != null) {
                builder.addFormDataPart("fileName", request.getFileName());
            }
            
            // 验证是否有内容输入
            if (!hasInputContent) {
                return buildErrorResponse("必须提供query、file或fileUrl其中之一");
            }
            
            // 构建请求
            Request httpRequest = new Request.Builder()
                    .url(directCreateUrl)
                    .addHeader("appId", appId)
                    .addHeader("timestamp", ts)
                    .addHeader("signature", signature)
                    .post(builder.build())
                    .build();
            
            // 发送请求
            try (Response response = client.newCall(httpRequest).execute()) {
                String responseBody = response.body().string();
                log.info("直接生成PPT结果: {}", responseBody);
                
                // 解析响应
                if (response.isSuccessful()) {
                    return JSONUtil.toBean(responseBody, PPTCreateResponse.class);
                } else {
                    log.error("直接生成PPT失败，状态码: {}, 响应: {}", response.code(), responseBody);
                    return buildErrorResponse("请求失败: " + response.code() + ", " + responseBody);
                }
            }
        } catch (Exception e) {
            log.error("直接生成PPT异常", e);
            return buildErrorResponse("系统异常: " + e.getMessage());
        }
    }
    
    /**
     * 构建错误响应
     */
    private PPTCreateResponse buildErrorResponse(String message) {
        PPTCreateResponse errorResponse = new PPTCreateResponse();
        errorResponse.setFlag(false);
        errorResponse.setCode(-1);
        errorResponse.setDesc(message);
        return errorResponse;
    }
} 